//
//  HomeViewController.m
//  A_Project_DLS151129_SQ
//
//  Created by 151129-49宋强 on 16/1/20.
//  Copyright © 2016年 www.lanou3g.com蓝鸥. All rights reserved.
//

#import "HomeViewController.h"
#import "FragmentTableViewCellOne.h"
#import "FragmentTableViewCellTwo.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface HomeViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, CarouselPictureDelegate>
@property (nonatomic, retain) NSMutableArray *photoDataArr;//轮播图数组
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *dataArr;//精选数据数组
@property (nonatomic, retain) UIScrollView *scrollerView;
@property (nonatomic, retain) UIScrollView *xianScollerView;
@property (nonatomic, retain) NSMutableArray *buttonArr;//button数组
@property (nonatomic, retain) UITableView *fragmentTableView;//碎片tableView
@property (nonatomic, retain) NSMutableArray *fragmentDataArr;//碎片数据数组
@property (nonatomic, assign) BOOL isLogin;//是否登录
@property (nonatomic, assign) NSInteger start;
@property (nonatomic, assign) NSInteger Tstart;
@property (nonatomic, retain) NSNumber *addTime;
@property (nonatomic, retain) NSMutableDictionary *dic;
@end

@implementation HomeViewController
- (void)dealloc
{
    [_photoDataArr release];
    [_tableView release];
    [_dataArr release];
    [_scrollerView release];
    [_xianScollerView release];
    [_buttonArr release];
    [_buttonArr release];
    [_fragmentTableView release];
    [_dic release];
    [super dealloc];
}
//View将要出现时重置位置
- (void)viewWillAppear:(BOOL)animated
{
    for (UIButton *btn in _buttonArr) {
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    [_buttonArr[0] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    _xianScollerView.contentOffset = CGPointZero;
    _scrollerView.contentOffset = CGPointZero;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"首页";
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    //创建嵌套三个tableView的ScrollerView
    [self creatScrollerView];
    //数据处理
    [self data];
    //fragmentTableView数据 处理
    [self creatFragmentData];
    //创建精选tableView
    [self creatTableView];
    //创建导航标题栏
    [self creatTribleView];
    //创建动态tableView
    [self creatDTTableView];
    //创建碎片tableView
    [self creatFragmentTableView];
     //初始化
    self.addTime = 0;
    self.start = 0;
    self.Tstart = 0;
    self.dataArr = [NSMutableArray array];
    self.fragmentDataArr = [NSMutableArray array];
    
    
    
}
//碎片tableView
- (void)creatFragmentTableView
{
    self.fragmentTableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH * 2, 0, WIDTH, HEIGHT - 50 - 64) style:UITableViewStylePlain];
    _fragmentTableView.delegate = self;
    _fragmentTableView.dataSource = self;
    _fragmentTableView.showsHorizontalScrollIndicator = NO;
    _fragmentTableView.showsVerticalScrollIndicator = NO;
    //注册第一种cell
    [_fragmentTableView registerClass:[FragmentTableViewCellOne class] forCellReuseIdentifier:@"fragmentCell"];
    //注册第二种cell
    [_fragmentTableView registerClass:[FragmentTableViewCellTwo class] forCellReuseIdentifier:@"fragmentCellTwo"];
    [self.scrollerView addSubview:_fragmentTableView];
    #pragma mark - 碎片的刷新和加载
     self.fragmentTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 刷新
        self.start = 0;
        [self creatFragmentData];
         }];
    //下拉加载
    self.fragmentTableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        self.start += 10;
        [self.dic setObject:self.addTime forKey:@"addtime"];
        [self creatFragmentData];
        [self.fragmentTableView.mj_footer endRefreshing];
    }];
    
}
//动态tableView
- (void)creatDTTableView
{
    if (!_isLogin) {
    
    // 如果没有登陆创建Lable And Button
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH + 120, 120, self.view.frame.size.width - 100, 150)];
        textLabel.numberOfLines = 3;
        textLabel.text = @"一个人, 好孤单\n\n不登陆, 没人爱";
        [self.scrollerView addSubview:textLabel];
        [textLabel release];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(WIDTH + 120, 270, 120, 60);
        button.backgroundColor = [UIColor greenColor];
        [button addTarget:self action:@selector(isLoginBtn) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:@"登陆" forState:UIControlStateNormal];
        [self.scrollerView addSubview:button];
       }
}
- (void)isLoginBtn
{
    NSLog(@"~~~~登陆");
}
#pragma mark - 创建标题导航按钮
- (void)creatTribleView
{
    NSArray *arrT = @[@"精选", @"动态", @"碎片"];
    //初始化按钮数组
    self.buttonArr = [NSMutableArray array];
    //添加三个按钮设置tag
    for (NSInteger i = 0; i < 3; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.frame = CGRectMake(i * WIDTH / 3, 0, WIDTH / 3  , 49);
        [btn setTitle:arrT[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.tag = i + 1;
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        [self.buttonArr addObject:btn];
        if (i == 0) {
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }
    }
    self.xianScollerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 49, WIDTH  , 1)];
    _xianScollerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_xianScollerView];
    [_xianScollerView release];
    _xianScollerView.contentSize = CGSizeMake(WIDTH, 1);
    _xianScollerView.showsHorizontalScrollIndicator = NO;
    _xianScollerView.showsVerticalScrollIndicator = NO;
    _xianScollerView.bounces = NO;
    UIView *xian = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 3, 1)];
    xian.backgroundColor = [UIColor redColor];
    [_xianScollerView addSubview:xian];
    [xian release];
    
    
}
//导航栏标题button触发方法
- (void)btnAction:(UIButton *)btn
{
    [_scrollerView setContentOffset:CGPointMake(WIDTH * (btn.tag - 1), 0)animated:YES] ;
    [_xianScollerView setContentOffset:CGPointMake(- (WIDTH / 3) * (btn.tag - 1), 0)];
    for (UIButton *btn in _buttonArr) {
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    
}
//创建ScrollerView
- (void)creatScrollerView
{
    self.scrollerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 50, WIDTH, HEIGHT - 50)];
    self.scrollerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_scrollerView];
    [_scrollerView release];
    _scrollerView.delegate = self;
    _scrollerView.contentSize = CGSizeMake(WIDTH* 3, HEIGHT - 50);
    _scrollerView.pagingEnabled = YES;
    _scrollerView.showsHorizontalScrollIndicator = NO;
    _scrollerView.showsVerticalScrollIndicator = NO;
    _scrollerView.bounces = NO;
}
//按钮颜色 偏移量联动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == _scrollerView) {
        [_xianScollerView setContentOffset:CGPointMake(- scrollView.contentOffset.x / 3, 0)animated:YES];
        NSInteger i = scrollView.contentOffset.x / WIDTH;
        for (UIButton *btn in _buttonArr) {
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        [_buttonArr[i] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        NSLog(@"%ld",i);
    }
        
    
}
//创建tableView
- (void)creatTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 50 - 64 )];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_scrollerView addSubview:_tableView];
    _tableView.tableHeaderView = [self.view viewWithTag:5000];
    [_tableView release];
    [_tableView registerClass:[HomeTableViewCell class] forCellReuseIdentifier:@"cell"];
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    #pragma mark - 精选加载和刷新
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.Tstart = 0;
        [self data];
    }];
   // 上拉加载
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        self.Tstart += 10;
        [self data];
        [self.tableView.mj_footer endRefreshing];
    }];

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //判断tableView
    if (tableView == _fragmentTableView) {
        return _fragmentDataArr.count;
    }
    return _dataArr.count;
}
//cell样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //判断tableView
    if (tableView == _fragmentTableView) {
        Model *m = _fragmentDataArr[indexPath.row];
        if (m.coverimg.length > 0) {
            FragmentTableViewCellOne * cell = [tableView dequeueReusableCellWithIdentifier:@"fragmentCell" forIndexPath:indexPath];
            [cell.headView sd_setImageWithURL:[NSURL URLWithString:m.icon]];
            cell.coverimg_wh = m.coverimg_wh;//传递图片比例参数
            cell.nameLabel.text = m.uname;
            cell.contentLabel.text = m.content;
            cell.timeLabel.text = m.addtime_f;
            cell.commentLabel.text = m.comment;
            cell.xinLabel.text = m.like;
            [cell.imgView sd_setImageWithURL:[NSURL URLWithString:m.coverimg]];
            return cell;
        }else{
            FragmentTableViewCellTwo *cell = [tableView dequeueReusableCellWithIdentifier:@"fragmentCellTwo" forIndexPath:indexPath];
            cell.nameLabel.text = m.uname;
            cell.contentLabel.text = m.content;
            cell.timeLabel.text = m.addtime_f;
            cell.commentLabel.text = m.comment;
            cell.xinLabel.text = m.like;

            [cell.headView sd_setImageWithURL:[NSURL URLWithString:m.icon]];
            return cell;
        }
    }else {
    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath] ;
    Model *m = _dataArr[indexPath.row];
    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:m.coverimg]];
    if ([m.name isEqualToString:@"音乐"]) {
        cell.imgView.image = [UIImage imageNamed:@"zanting.png"];
    }
    cell.nameLabel.text = [m.name stringByAppendingString:m.enname];
    cell.contentLabel.text = m.content;
    cell.titleLabel.text = m.title;
    return cell;
    }
   }
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _fragmentTableView) {
        Model *m = _fragmentDataArr[indexPath.row];
        if (m.coverimg.length > 0) {
            CGFloat labelH = [FragmentTableViewCellOne heightWithText:m.content];
            CGFloat imgH = [FragmentTableViewCellOne heightWithImg:m.coverimg_wh];
            return labelH + imgH + 130;
        }else{
            CGFloat h = [FragmentTableViewCellTwo heightWithText:m.content];
            return h + 120;
        }
    }
    Model *m = _dataArr[indexPath.row];
    //title高度
    CGFloat h = [HomeTableViewCell heightWithText:m.title];
    CGFloat hh = [HomeTableViewCell heightWithText:m.content];
    return hh + 230 + h;
}
//fragmentTableView数据处理
- (void)creatFragmentData
{
    NSString *urlStr = @"http://api2.pianke.me/timeline/list";
    //self.dic = @{ @"start": @(self.start), @"client": @2, @"limit": @10,};
    
    
    self.dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@(self.start),@"start",@2,@"client",@10,@"limit", nil];
    [PWNetWorking POSTWithURL:urlStr body:_dic completion:^(id result) {
        NSArray *arr = result[@"data"][@"list"];
        NSArray *tempArr = [Model modelHanderWithArray:arr];
        self.addTime = [tempArr.lastObject addtime];
        if (self.start == 0) {
        [self.fragmentDataArr removeAllObjects];//初始化数组
        }
        for (Model *m in tempArr) {
        [self.fragmentDataArr addObject:m];
        }
        [_fragmentTableView reloadData];
        [self.fragmentTableView.mj_header endRefreshing];
      }];
}
//cell点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _fragmentTableView) {
        Model *m = _fragmentDataArr[indexPath.row];
        ReadWebVC *webVC = [[ReadWebVC alloc] init];
        webVC.contenId = m.contentid;
        webVC.collectionModel = m;
        [self.navigationController pushViewController:webVC animated:YES];
        [webVC release];
    }else{
        Model *m = _dataArr[indexPath.row];
        if ([m.name isEqualToString:@"Ting"]) {
            MusicPlayViewController *musicVC = [[MusicPlayViewController alloc] init];
            musicVC.mm = m;
            [self.navigationController pushViewController:musicVC animated:YES];
            //[musicVC release];
        }else{
        ReadWebVC *webVC = [[ReadWebVC alloc] init];
        webVC.contenId = m.id;
        webVC.collectionModel = m;
        [self.navigationController pushViewController:webVC animated:YES];
        [webVC release];
        }
    }
}
//数据处理
- (void)data
{
    NSString *URLStr = @"http://api2.pianke.me/pub/today";
    NSDictionary *bodyDic =@{@"start":@(self.Tstart), @"client": @"2", @"limit":@"10"};
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [sessionManager POST:URLStr parameters:bodyDic progress:^(NSProgress * _Nonnull uploadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //获取轮播图数组信息
        //JSON解析
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = dic[@"data"][@"list"];
        //tableView数组
        NSArray *tempArr = [Model modelHanderWithArray:arr];
        if (self.Tstart == 0) {
            [self.dataArr removeAllObjects];
        }
        for (Model *m in tempArr) {
          [self.dataArr addObject:m];
        }
        [self.tableView reloadData];
         [self.tableView.mj_header endRefreshing];
        NSArray *photoArr = dic[@"data"][@"carousel"];
        //轮播图数组
        self.photoDataArr = [Model modelHanderWithArray:photoArr];
        [self creatRoller];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"错误信息:%@",error);
    }];
}
//轮播图
- (void)creatRoller
{  //图片数组
    NSMutableArray *photos = [NSMutableArray array];
    NSMutableArray *urlArr = [NSMutableArray array];
    for (Model *m in _photoDataArr) {
        [photos addObject:m.img];
        [urlArr addObject:m.url];
    }
    //调用封装方法
    CarousePhotoView *photoView = [[CarousePhotoView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 150) timeInterval:5 imageUrlArr:photos urlArr:urlArr];
    photoView.delegate = self;
    [_scrollerView addSubview:photoView];
    [photoView release];
    self.tableView.tableHeaderView = photoView;
 }
//轮播图协议方法
- (void)pushWithUrl:(NSString *)url
{
    NSString *str = [url substringFromIndex:15];
    ReadWebVC *webVC = [[ReadWebVC alloc] init];
    webVC.contenId = str;
    NSLog(@"%@",str);
    [self.navigationController pushViewController:webVC animated:YES];
    [webVC release];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
